﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Budget.IncomeWCFProxy;
using Newtonsoft.Json;
using Budget.HelperClasses;

namespace Budget.Data
{
	public partial class Incomes : System.Web.UI.Page
	{
		protected void Page_Load( object sender, EventArgs e )
		{
			string action = Request.Form["xaction"];
			if ( !string.IsNullOrEmpty( action ) )
			{
				switch ( action )
				{
					case "create":
						CreatIncome();
						break;
					case "update":
						UpdateIncome();
						break;
					case "destroy":
						DeleteIncome();
						break;
					default:
						ListIncome();
						break;
				}
			}
		}

		#region Actions

		private void CreatIncome()
		{
			Income newIncome = JsonConvert.DeserializeObject<Income>( Request.Form["data"] );
			newIncome.Timestamp = DateTime.Now;

			JsonResponse<Income> response = new JsonResponse<Income>();

			try
			{
				WCFHelper.Using<IncomeServiceClient>( svc => svc.Save( newIncome ) );

				response.Success = true;
				response.Message = "Successfully created Income object.";
			}
			catch ( Exception ex )
			{
				response.Success = false;
				response.Message = "An error occurred while creating Income object.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		private void UpdateIncome()
		{
			Income updatedIncomeDetails = JsonConvert.DeserializeObject<Income>( Request.Form["data"] );
			updatedIncomeDetails.Timestamp = DateTime.Now;

			JsonResponse<Income> response = new JsonResponse<Income>();

			try
			{
				Income inc = null;
				WCFHelper.Using<IncomeServiceClient>( svc => inc = svc.GetIncomeById( updatedIncomeDetails.IncomeId ) );

				inc.Description = updatedIncomeDetails.Description;
				inc.Amount = updatedIncomeDetails.Amount;
				inc.IsActive = updatedIncomeDetails.IsActive;
				inc.Timestamp = DateTime.Now;

				WCFHelper.Using<IncomeServiceClient>( svc => svc.Save( inc ) );

				response.Success = true;
				response.Message = "Successfully updated Income object.";
			}
			catch ( Exception ex )
			{
				response.Success = false;
				response.Message = "An error occurred while updating Income object.";
			}

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		private void DeleteIncome()
		{
			throw new NotImplementedException();
		}

		private void ListIncome()
		{
			JsonResponse<Income> response = new JsonResponse<Income>();

			WCFHelper.Using<IncomeServiceClient>( svc => response.Data = svc.GetAll() );
			
			response.Count = response.Data.Count();
			response.Success = true;
			response.Message = "Successfully retrieved all Income objects.";

			ltrJsonResponse.Text = JsonConvert.SerializeObject( response );
		}

		#endregion

	}
}
